<template>
  <div>
    <a-row :gutter="24">
      <a-col :span="24">
        <a-card
          class="project-list"
          :loading="platformLoading"
          style="margin-bottom: 24px"
          :bordered="false"
          title="任务统计"
          :body-style="{ padding: 0 }"
        >
          <div class="extra-wrapper" slot="extra">
            <a-radio-group :value="timeType" @change="handleGetAnalysis">
              <a-radio-button :value="1">
                周
              </a-radio-button>
              <a-radio-button :value="2">
                月
              </a-radio-button>
            </a-radio-group>
          </div>
        </a-card>
      </a-col>
      <a-col :sm="12" :md="8" :xl="6" :style="{ marginBottom: '24px' }">
        <a-card :title="`本${timeType == 1?'周':'月'}任务数`" :loading="platformLoading">
          <div style="height: 200px">
            <AWM-rate name="镜头数" :rateShot="rateShot"></AWM-rate>
          </div>
        </a-card>
      </a-col>
      <a-col :sm="12" :md="8" :xl="12" :style="{ marginBottom: '24px' }">
        <a-card :loading="platformLoading">
          <div class="lens-statistical">
            <div class="lens-statistocal-title">
              <h4>
                <span> {{ userData.detailName }} {{timeType == 1?'周':'月'}}镜头制作量 </span>
                
              </h4>
            </div>
            <div class="lens-statistocal-body">
              <div class="lens-statistocal-time">
                <h6>{{ weekShot.allNum }}</h6>
              </div>
              <div class="lens-statistocal-num">
                <h6>{{ weekShot.allNum - weekShot.lastWeekNum }}
                  <span>
                    <a-icon
                      type="caret-up"
                      v-if="weekShot.allNum - weekShot.lastWeekNum > 0"
                      two-tone-color="#f81d22"
                    />
                    <a-icon
                      type="caret-down"
                      v-else-if="weekShot.allNum - weekShot.lastWeekNum < 0"
                      two-tone-color="#52c41a"
                    />
                  </span></h6>
              </div>
            </div>
            <div class="lens-statistocal-footer">
              <div class="lens-statistocal-item">
                <div class="lens-statistocal-icon">
                  <a-icon type="check-circle" />
                </div>
                <div class="lens-statistocal-content">
                  <div class="content-num">{{ weekShot.allTime || 0 }}</div>
                  <div>新做镜头时长(秒)</div>
                </div>
              </div>
              <div class="lens-statistocal-item">
                <div class="lens-statistocal-icon">
                  <a-icon type="reload" />
                </div>
                <div class="lens-statistocal-content">
                  <div class="content-num">{{ weekShot.editTime }}</div>
                  <div>修改镜头时长(秒)</div>
                </div>
              </div>
              <div class="lens-statistocal-item">
                <div class="lens-statistocal-icon">
                  <a-icon type="area-chart" />
                </div>
                <div class="lens-statistocal-content">
                  <div class="content-num">上{{timeType == 1?'周':'月'}}完成时长(秒) {{ weekShot.lastWeekTime || 0 }}</div>
                  <div>上{{timeType == 1?'周':'月'}}完成任务数 {{ weekShot.lastWeekNum || 0 }}</div>
                </div>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :sm="12" :md="8" :xl="6" :style="{ marginBottom: '24px' }">
        <a-card title="各等级镜头数" :loading="platformLoading">
          <div style="height: 200px">
            <AWM-bar :chartData="levelShotList" name="镜头数"></AWM-bar>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :sm="12" :md="8" :xl="6" :style="{ marginBottom: '24px' }">
        <a-card title="新做镜头占比" :loading="platformLoading">
          <div style="height: 200px">
            <AWM-pai :chartData="newRateData" :radius="[30, 60]" :height="175"></AWM-pai>
          </div>
        </a-card>
      </a-col>
      <a-col :sm="12" :md="8" :xl="12" :style="{ marginBottom: '24px' }">
        <a-card :loading="platformLoading">
          <div style="height: 255px">
            <AWM-line :chartData="taskLineData" :lineList="taskLineParameter" :name="`近4${timeType == 1?'周':'月'}任务时长`"></AWM-line>
          </div>
        </a-card>
      </a-col>
      <a-col :sm="12" :md="8" :xl="6" :style="{ marginBottom: '24px' }">
        <a-card title="新做与修改同比变化" :loading="platformLoading">
          <div style="height: 200px">
            <AWM-bar :chartData="taskBarData" :lineList="barList"></AWM-bar>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :sm="12" :md="8" :xl="6" :style="{ marginBottom: '24px' }">
        <a-card :loading="platformLoading" :title="`上${timeType == 1?'周':'月'}任务数`">
          <div style="height: 250px">
            <AWM-rate name="镜头数" :rateShot="taskNumList"></AWM-rate>
            <!-- <AWM-bar :chartData="taskNumList" name="name"></AWM-bar> -->
            <!-- :chartData="barData" -->
          </div>
        </a-card>
      </a-col>

      <a-col :sm="12" :md="8" :xl="12" :style="{ marginBottom: '24px' }">
        <a-card :loading="platformLoading" title="本月任务达标情况">
          <div style="height: 250px">
            <div style="float: left; display: flex; margin-top: 120px"></div>
            <level-star :levelRateList="levelRateList" :userData="userData" :starList="starList"></level-star>
          </div>
        </a-card>
      </a-col>
      <a-col :sm="12" :md="8" :xl="6" :style="{ marginBottom: '24px' }">
        <a-card title="等级信息" :loading="platformLoading">
          <a-tooltip title="等级规则" slot="extra" style="cursor:pointer;">
            <a-icon type="info-circle-o" @click="handleLookLevelDetails"/>
          </a-tooltip>
          <div style="position: relative; height: 250px">
            <div>
              <a-descriptions bordered size="small" :column="{ xl: 1 }">
                <a-descriptions-item label="姓名">
                  {{ userData.detailName }}
                </a-descriptions-item>
                <a-descriptions-item label="当前等级">
                  {{ userData.nonceLevel.name }}
                  {{ userData.nextLevel.name ? ` -> ${userData.nextLevel.name}` : '' }}
                </a-descriptions-item>
                <a-descriptions-item label="申请升级">
                  <span v-if="userData.applyTime">{{ userData.applyTime }}</span>
                  <span v-else-if="dId == userInfo.id">
                    <a-button size="small" type="primary" @click="handleUp" :loading="loading">申请升级</a-button>
                  </span>
                  <span v-else> -- </span>
                </a-descriptions-item>
                <a-descriptions-item label="升级情况"> 累计<a @click="handleClickMonth"> {{ userData.passNum }} </a>个月达标 </a-descriptions-item>
                <a-descriptions-item label="降级情况"> 累计<a @click="handleClickMonth"> {{ userData.subNum }} </a>个月不达标 </a-descriptions-item>
              </a-descriptions>
            </div>
            <!-- <div style="position: absolute;top:-80px;bottom:0;left:0;right:0;"> -->
            <!-- <AWM-bar :chartData="personBar" name="镜头数" :lengthways="true" :chartScorll="true"></AWM-bar> -->
            <!-- </div> -->
          </div>
        </a-card>
      </a-col>
    </a-row>
    <level-detail
      :visible='levelDetail.visible'
      :userLevels="userLevels"
      :levelList="levelList"
      :levelNum="userData.nonceLevel.levelNum"
      @cancel="handleLevelDetailCancel"
    ></level-detail>
    <level-start-modal
      :visible='visible'
       @cancel="handleCancel"
    ></level-start-modal>
  </div>
</template>
<script>
import moment from 'moment'
import { ChartCard, MiniArea, MiniBar, MiniProgress, Bar, Trend, MiniSmoothArea } from '@/components'
import { baseMixin } from '@/store/app-mixin'
import { taskByWeekStatistics } from '@/api/system'
import { monthTaskGetMonthTask, monthTaskGetMonthTaskBySelf, userApplyUp } from '@/api/login'
import AWMPai from '@/components/AWMechart/pai'
import AWMLine from '@/components/AWMechart/line'
import AWMBar from '@/components/AWMechart/bar'
import AWMRate from '@/components/AWMechart/rate'
import { mapGetters } from 'vuex'
import LevelStar from './modules/LevelStar'
import { renderList } from './js/render'
import levelStartModal from './modules/levelStartModal'
import LevelDetail from './modules/levelDetail'


export default {
  name: 'userAnalysis',
  mixins: [baseMixin],
  components: {
    ChartCard,
    MiniArea,
    MiniBar,
    MiniProgress,
    Bar,
    Trend,
    MiniSmoothArea,
    AWMPai,
    AWMLine,
    AWMBar,
    AWMRate,
    LevelStar,
    levelStartModal,
    LevelDetail
  },
  data() {
    return {
      timeType: 1,
      dKey: null,
      dId: null,
      userData: {
        nonceLevel: {},
        nextLevel: {},
        passNum: 0,
        subNum: 0,
        detailName: '',
        applyTime: '',
      },
      levelRateList: [],
      rateShot: {
        total: 0,
        finish: 0,
      },
      weekShot: {
        allNum: 0, //  已完成
        subTime: 0, //  时长完成任务对比
        allTime: 0, //  总时长
        editTime: 0, // 返修时长

        lastWeekTime: 0, // 上周时长
        lastWeekNum: 0, // 上周任务数
      },
      taskNumList: {},
      levelShotList: [],
      newRateData: [],
      myChart: null,
      platformLoading: false,
      timeValue: null,

      taskLineData: [],
      taskLineParameter: [
        { key: 'time', name: '完成时长' },
        { key: 'allTime', name: '总时长' },
      ],
      taskBarData: [],
      barList: [
        { key: 'count', name: '新做' },
        { key: 'newCount', name: '修改' },
      ],
      plineData: [],
      plineList: [
        { key: 'levelA', name: 'A' },
        { key: 'levelB', name: 'B' },
        { key: 'levelC', name: 'C' },
        { key: 'levelD', name: 'D' },
      ],
      personBar: [],
      starList: [],
      loading: false,
      visible:false,
      levelDetail:{
        visible:false,
      },
      userLevels: [],
      levelList:[],
    }
  },
  filters: {},
  computed: {
    ...mapGetters({
      userInfo: 'userInfo',
    }),
  },
  created() {
    let { key, id } = this.$route.params
    this.dKey = key || 'user'
    this.dId = id || this.userInfo.id
    this.getAnalysis()
    this.getSelfAnalysis()
  },
  mounted() {},
  methods: {
    handleLookLevelDetails(){
      this.levelDetail.visible = true;
    },
    handleGetAnalysis(e) {
      let str = e.target.value
      this.timeType = str
      this.getSelfAnalysis()
    },
    handleUp() {
      this.loading = true
      userApplyUp()
        .then((res) => {
          this.$message.success('申请成功!')
        })
        .finally(() => {
          this.loading = false
        })
    },
    getSelfAnalysis() {
      let { dKey, dId, timeType } = this
      let typeJSON = {
        user: 3,
        studios: 2,
        project: 1,
      }
      let weekName = {
        0: '本周',
        1: '上一周',
        2: '上两周',
        3: '上三周',
      }
      if(timeType == 2){
        weekName = {
          0: '本月',
          1: moment().startOf('month').subtract(1,'month').format('M')+'月',
          2: moment().startOf('month').subtract(2,'month').format('M')+'月',
          3: moment().startOf('month').subtract(3,'month').format('M')+'月',
        }
      }
      this.platformLoading = true
      taskByWeekStatistics({ detailId: dId, type: typeJSON[dKey], timeType }).then((res) => {
        if (res.data) {
          let levelList = res.data.level.sort((a, b) => a.levelNum - b.levelNum)
          let newRateData = [],
            taskLineData = []
          this.detailName = res.data.detailName
          res.data.weeks.forEach((v, i) => {
            if (i == 0) {
               let levelShotList = [] // levelShotList 各等级数量
              let taskBarData = [] // levelShotList 各等级数量

              // 月镜头制作量 统计 start
              let weekShot = {
                allNum: v.finishNumByShot || 0, //
                allTime: v.finishTimeLength || 0, //
                editTime: v.retakeTimeLength || 0,
              }
              this.weekShot = weekShot
              // 月镜头制作量 统计 end
             

              // 本月任务数 赋值 start
              let rateShot = {
                total: v.totalNumByShot || 0, // + (v.totalNumByAssets || 0),
                finish: v.finishNumByShot || 0, // + (v.finishNumByAssets || 0),
              }
              this.rateShot = rateShot
              // 本月任务数 赋值 end

              // 各等级任务数 赋值 start
              if (v.levelNumByShot)
                for (let it in v.levelNumByShot) {
                  levelShotList.push({ name: it, count: v.levelNumByShot[it] || 0 })
                  // 新做与修改同比变化 start
                  taskBarData.push({
                    name: it,
                    count: v.levelNumByShot[it] || 0,
                    newCount: v.retakeNumLevelByShot ? v.retakeNumLevelByShot[it] || 0 : 0,
                  })
                  // 新做与修改同比变化 end
                }
              // 各等级任务数 赋值 end
              this.levelShotList = levelShotList
              this.taskBarData = taskBarData
              
            }

            if (i == 1) {
              // 上月任务数 start
              let taskNumList = {
                total: v.totalNumByShot || 0, // + (v.totalNumByAssets || 0),
                finish: v.finishNumByShot || 0, // + ( v.finishNumByAssets || 0 )
              }
              this.taskNumList = taskNumList
              // 上月任务数 end

              // 月镜头制作量(上月) 统计 start
              let weekShot = {
                lastWeekTime: v.finishTimeLength || 0,
                lastWeekNum: v.finishNumByShot || 0,
              }
              this.weekShot = { ...this.weekShot, ...weekShot }
              // 月镜头制作量(上月) 统计 end
            }
            // 新做镜头占比 赋值 start
            newRateData.push({
              name: weekName[i],
              value: v.finishNumByShot || 0,
            })
            // 新做镜头占比 赋值 end

            //近4月任务时长  赋值 start
            taskLineData.push({
              name: weekName[i],
              time: v.finishTimeLength || 0,
              allTime: v.totalTimeLength || 0,
            })
            //近4月任务时长  赋值 end
          })

          this.newRateData = newRateData.reverse()
          this.taskLineData = taskLineData.reverse()

          let personBar = [],
            userLevelBarData = [],
            plineList = []
          res.data.userSort &&
            res.data.userSort.forEach((v, i) => {
              personBar.push({
                name: v.detailName,
                count: v.number || 0,
              })
            })
          res.data.userLevel && 
            res.data.userLevel.forEach((v, i) => {
              let aitem = {
                name: v.userName,
              }
              // shotLevel
              levelList.forEach((it) => {
                plineList.push({ key: it.name, name: it.name })
                if (v.shotLevel) {
                  aitem[it.name] = v.shotLevel[it.name] || 0
                } else {
                  aitem[it.name] = 0
                }
              })
              userLevelBarData.push(aitem)
            })
          this.personBar = personBar
          this.userLevelBarData = userLevelBarData
        }
      }).finally(()=>this.platformLoading = false)
    },
    getAnalysis() {
      let { dKey, dId } = this
      let fun = monthTaskGetMonthTask
      if (this.dId == this.userInfo.id) {
        fun = monthTaskGetMonthTaskBySelf
      }
      fun({ userId: dId, byMonth: 1 }).then((res) => {
        console.log(res)
        let levelList = res.data.levels.sort((a, b) => b.levelNum - a.levelNum)
        this.levelList = levelList;
        this.userData.nonceLevel = res.data.nonceLevel || {}
        this.userData.nextLevel = res.data.nextLevel || {}
        this.userData.passNum = res.data.passNum || 0
        this.userData.subNum = res.data.subNum || 0
        this.userData.applyTime = res.data.applyTime || ''

        let taskJson = res.data.monthTask ? JSON.parse(res.data.monthTask.taskJson) : ''
        let levelData = []
        levelList.forEach((v) => {
          if (taskJson.integral && taskJson.integral[v.name]) {
            // taskJson.integral
            levelData.push({ levelName: v.name, ...taskJson.integral[v.name] })
          } else {
            levelData.push({ levelName: v.name, rate: 0, integral: 0, needIntegral: 0, nextNeedIntegral: 0 })
          }

          // scoreInfo: scoreInfo[key],
          // scoreInfo: scoreInfo[key],

          let key = v.name.substr(0, 1)
          //
          // name
        })
        this.levelRateList = levelData
        let taskLevels = res.data.taskLevels.sort((a, b) => b.levelNum - a.levelNum)

        
        let starList = []
        let scoreInfo = taskJson.scoreInfo || {}
        taskLevels.forEach((v) => {
          let it = {
            name: v.name,
            scoreInfo: scoreInfo[v.name],
          }
          starList.push(it)
        })


        this.starList = starList
        this.userLevels = res.data.userLevels.filter(v=>v.proTypeId == 17).map(v=>{
          let mneedJson = (v.mneedJson) ? JSON.parse(v.mneedJson):{}
          return {
            ...v,
            ...mneedJson.integral || {}
          }
        })

        // "{"task": {"C类": {"A": 100}}, "score": {"A": {"3": 1}}, "integral": {"C类": {"rate": 0.25, "integral": 200.00, "needIntegral": 800}}, "scoreInfo": {"A": {"score_3": 100, "maxScore_3": 30}}, "scoreCheck": false, "nextScoreCheck": true}"

        //   <!-- "{"task": {"C类": {"A": 300, "B": 20, "C": 10}}, "score": {"A": {"1": 1, "3": 1}, "B": {"3": 1}, "C": {"2": 1}},
        // "integral": {"C类": {"rate": 2.08, "integral": 625.00, "needIntegral": 300}}, "scoreCheck": false,
        // "nextScoreCheck": false}" -->
      })
    },
    handleCancel(){
      this.visible = false
    },
    handleClickMonth(){
      this.visible = true
    },
    handleLevelDetailCancel(){
      this.levelDetail.visible = false
    },
  },
}
// "{"levelNumByShot": {"B": 1, "C": 1}, "totalNumByShot": 3, "finishNumByShot": 1, "retakeNumByShot": 2, "totalTimeLength": 0, "finishTimeLength": 0, "retakeTimeLength": 0, "hisDelayNumByShot": 0, "nowDelayNumByShot": 0, "hisDelayTimeLength": 0, "nowDelayTimeLength": 0}"
</script>

<style lang="less" scoped>
.all-star-wrap {
  display: flex;
  justify-content: space-around;
  margin-top: 25px;
  .level-wrap {
    width: 10%;
    text-align: center;
    margin-top: 21px;
    li {
      font-weight: bold;
      border: 1px solid #ccc;
      line-height: 42px;
      &:nth-child(2) {
        border-top: none;
      }
    }
  }
  .star-wrap-wrap {
    width: 30%;
    text-align: center;
    span {
      font-weight: bold;
    }
    .red {
      color: #ee6666;
    }
    .green {
      color: #91cc75;
    }
  }
}

// /deep/
// .ant-card{
//   background-color: #202948;
//   .ant-card-head{
//     border-bottom-color:transparent;
//   }
// }
.star-wrap {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  border-top: 1px solid #ccc;
  &:nth-child(3) {
    border-top: none;
  }
  li {
    width: 50%;
  }
  // &.star-wrap-next {
  //   padding-top: 10px;
  // }
}
.progress-wrap {
  display: flex;
  justify-content: space-around;
  align-items: center;
  .progress-box {
    position: relative;
    span {
      position: absolute;
      display: inline-block;
      top: 85%;
      left: 50%;
      transform: translate(-50%, 0);
    }
  }
}
.user-level-details {
  line-height: 30px;
}
.lens-statistical {
  .lens-statistocal-title {
    position: relative;
    text-align: center;
    width: 60%;
    margin: 0 auto;
    // height: 100px;
    h4 {
      position: relative;
      display: inline-block;
      padding: 5px 20px;
      background-color: #fff;
      text-align: center;
      margin-bottom: 0;
      // left: 50%;
      // top: 50%;
      // transform: translate(-50%,-50%);
      font-size: 20px;
      z-index: 1;
      span {
        font-weight: bold;
        color: #fae898;
      }
    }
    &:before {
      content: '';
      position: absolute;
      top: 50%;
      left: 0;
      right: 0;
      height: 2px;
      background-color: #fae898;
      z-index: 0;
    }
  }
  .lens-statistocal-body {
    display: flex;
    justify-content: center;
    align-content: center;
    & > div {
      padding: 30px;
      h6 {
        margin: 0;
        line-height: 75px;
        color: inherit;
      }
    }
    .lens-statistocal-time {
      color: #fae898;
      font-size: 120px;
    }
    .lens-statistocal-num {
      color: #9ba8d5;
      font-size: 100px;
      span {
        font-size: 25px;
        font-weight: bold;
      }
    }
  }
  .lens-statistocal-footer {
    display: flex;
    justify-content: space-between;
    margin-top: 15px;
    height: 50px;
    .lens-statistocal-item {
      display: flex;
      align-content: center;
      padding: 0 10px;
      &:nth-child(2) {
        .lens-statistocal-icon {
          color: #be63a8;
        }
      }
      &:nth-child(3) {
        .lens-statistocal-icon {
          color: #be7262;
        }
        .lens-statistocal-content {
          text-align: left;
        }
      }
      .lens-statistocal-icon {
        padding: 6px;
        line-height: 40px;
        font-size: 30px;
        color: #63c0cf;
      }
      .lens-statistocal-content {
        font-size: 14px;
        text-align: center;
        margin-left: 5px;
        min-width: 100px;
        color: #9ba8d5;
        font-weight: bold;
        // .content-num {
        //   font-size: 18px;
        // }
      }
    }
  }
}
</style>
